using FytSoa.Application.Erp.Param;
using FytSoa.Common.Enum;
using FytSoa.Common.Extensions;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Masuit.Tools.Reflection;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-采购申请单服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpPurchaseApplyService : IApplicationService 
{
    private readonly SugarRepository<ErpPurchaseApply> _thisRepository;
    private readonly SugarRepository<ErpProduceOrder> _orderRepository;
    private readonly SugarRepository<ErpPurchaseApplyProduct> _applyProductRepository;
    private readonly ErpOperateLogService _operateLogService;
    public ErpPurchaseApplyService(SugarRepository<ErpPurchaseApply> thisRepository
        ,SugarRepository<ErpProduceOrder> orderRepository
    ,SugarRepository<ErpPurchaseApplyProduct> applyProductRepository
    ,ErpOperateLogService operateLogService)
    {
        _thisRepository = thisRepository;
        _orderRepository = orderRepository;
        _applyProductRepository = applyProductRepository;
        _operateLogService = operateLogService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpPurchaseApplyDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id!=0,m=>m.OrderId==param.Id)
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key))
            .Includes(m=>m.Employee)
            .Includes(m=>m.Order)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpPurchaseApplyDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpPurchaseApplyDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .OrderByDescending(m=>m.Id)
            .FirstAsync(m=>m.OrderId==id);
        return model.Adapt<ErpPurchaseApplyDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(ErpPurchaseApplyAddParam param)
    {
        var toDay = await _thisRepository.CountAsync(m=>m.CreateTime.ToString("yyyy-MM")==DateTime.Now.ToString("yyyy-MM"));
        param.Apply.Number = "PSQ".ResNumber(toDay, "yyyyMM");
        param.Apply.ApplyPersonId = AppUtils.EmployeeId;
        var applyId=await _thisRepository.InsertReturnSnowflakeIdAsync(param.Apply.Adapt<ErpPurchaseApply>());

        foreach (var item in param.Produce)
        {
            item.ApplyId = applyId;
        }
        
        // 修改申请物料状态
        await _orderRepository.UpdateAsync(m => new ErpProduceOrder()
        {
            IsApply = true
        },m=>m.Id==param.Apply.OrderId);

        await _applyProductRepository.InsertRangeAsync(param.Produce.Adapt<List<ErpPurchaseApplyProduct>>());
        
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateIds = new List<long>(){param.Apply.OrderId,applyId},
            Type = (int)ErpOperateEnum.ProduceApply,
            Remark = "申请物料操作：【"+param.Apply.Number+"】"
        });
       
    }

    /// <summary>
    /// 更新状态
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task ModifyStatusAsync(ErpPurchaseApplyStatusParam param)
    {
        if (param.Status==ErpProduceApplyEnum.OutStock)
        {
            //判断状态是否可领取
            var isAny = await _thisRepository.IsAnyAsync(m => param.Ids.Contains(m.Id));
            if (!isAny)
            {
                throw new BusinessException("没有可领取的物料~");
            }
        }
        await _thisRepository.UpdateAsync(m => new ErpPurchaseApply()
        {
            Status = param.Status
        },m=>param.Ids.Contains(m.Id));
        
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateIds = param.Ids,
            Type = (int)ErpOperateEnum.ProduceApply,
            Remark = "变更了申请物料状态：【"+param.Status.GetDescription()+"】"
        });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
